package com.yhsimon.realm.member.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.yhsimon.realm.member.constant.BeanUsageCodeEnum;
import com.yhsimon.realm.member.dto.user.BeanSeckillDto;
import com.yhsimon.realm.member.entity.user.BeanBillEntity;
import com.yhsimon.realm.member.entity.user.BeanEntity;
import com.yhsimon.realm.member.mapper.BeanBillMapper;
import com.yhsimon.realm.member.mapper.BeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@RabbitListener(queues = "bean.seckill.queue")
@Component
public class BeanSeckillListener {

    @Autowired
    private BeanMapper beanMapper;

    @Autowired
    private BeanBillMapper beanBillMapper;

    @RabbitHandler
    public void beanSeckillListener(BeanSeckillDto beanSeckillDto, Channel channel, Message message) throws IOException {
        try {
            log.info("BeanSeckillListener: beanSeckillListener: 创建仙豆秒杀账单,beanSeckillDto 基本信息如下: {}", beanSeckillDto);
            BeanEntity beanEntity = beanMapper.selectOne(new QueryWrapper<BeanEntity>().eq("user_id", beanSeckillDto.getUserId()));
            beanEntity.setBalance(beanEntity.getBalance()+beanSeckillDto.getCount());
            log.info("BeanSeckillListener: beanSeckillListener: 更新用户仙豆余额");
            beanMapper.updateById(beanEntity);
            BeanBillEntity beanBillEntity = BeanBillEntity.builder()
                    .balanceChangeValue(beanSeckillDto.getCount())
                    .usageMode(BeanUsageCodeEnum.ACTIVITY.getCode())
                    .balance(beanEntity.getBalance())
                    .userId(beanEntity.getUserId())
                    .build();
            log.info("BeanSeckillListener: beanSeckillListener: 保存仙豆账单");
            beanBillMapper.insert(beanBillEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("BeanSeckillListener: beanSeckillListener: 消费beanSeckillDto失败");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
